package com.enba.boot.security.jwt;

import com.enba.boot.security.entity.IUser;
import com.enba.boot.security.service.JwtUserService;
import java.util.List;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class JwtUserDetailsService implements UserDetailsService {

  private final JwtUserService userService;

  public JwtUserDetailsService(JwtUserService userService) {
    this.userService = userService;
  }

  /**
   * @param username 用户名
   * @return UserDetails
   * @throws UsernameNotFoundException 用户不存在
   */
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 获取用户信息并缓存
    IUser user = userService.getUserByUsername(username);
    if (user == null) throw new UsernameNotFoundException("用户{" + username + "}不存在");

    // 获取角色列表并缓存
    List<String> roleList = userService.getRoleList(user.getId());

    // 获取权限列表并缓存
    List<String> permissionList = userService.getPermissionList(user.getId());

    return new JwtUserDetails(user, roleList, permissionList);
  }
}
